package com.me.TextMissed_a1;


import java.util.Locale;

import com.me.TextMissed_a1.MyAppWidget;

import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MyAppWidget extends AppWidgetProvider {
	
	private Toast toast;	
	public static final String UPDATE_ONDEMAND = "com.me.TextMissed_a1.UPDATE_ONDEMAND";
	public static final String UPDATE_PREFERENCE = "com.me.TextMissed_a1.UPDATE_PREFERENCE";
	private static final String ImageButton = null;
	
	private static String myTextSMS = null;

	
	//Automatic updater
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onUpdate ");
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		
		//get configuration language
		Configuration config = context.getResources().getConfiguration();
		Locale.getDefault();
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onUpdate Configuration config AFTER: "+config.locale);
		
		for (int i = 0; i < appWidgetIds.length; i++) {
			int appWidgetId = appWidgetIds[i];
			//Get RemoteViews
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
			
			//Update layout
			updateWidgetLayout(views, context,appWidgetId);
			
	        
			 // Klik do otwarcia wiadomosci sms
	        Intent intent = new Intent();
	        intent.setAction(WidgetReceiver.WIDGET_INTENT_SMS);
	        intent.setClassName(WidgetReceiver.class.getPackage().getName(), WidgetReceiver.class.getName());

	        PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
	        views.setOnClickPendingIntent(R.id.tvWidgetText1, pendingIntent);
	        views.setOnClickPendingIntent(R.id.tvWidgetText2, pendingIntent);
	        

	        // Klik do otwarcia rejestru nie odebranych polaczen
	        intent.setAction(WidgetReceiver.WIDGET_INTENT_CALL);
	        intent.setClassName(WidgetReceiver.class.getPackage().getName(), WidgetReceiver.class.getName());

	        PendingIntent pendingIntentCall = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
	        views.setOnClickPendingIntent(R.id.tvWidgetText3, pendingIntentCall);
	        //views.setOnClickPendingIntent(R.id.tvWidgetText4, pendingIntentCall);		
			
			
			//update widget
			appWidgetManager.updateAppWidget(appWidgetId, views);	
		}
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onReceive "+ context.getString(R.string.tvWidgetText1));
		super.onReceive(context, intent);
		
		if(intent.getAction().equals(UPDATE_ONDEMAND)) {
			myTextSMS = intent.getStringExtra("WidgetTextSMS");
			String myTextCall = intent.getStringExtra("WidgetTextCALL");
			
			updateWidget(context, myTextSMS, myTextCall);
			Log.d("_TextMissed_a1_", "Widget onReceive SMS "+ myTextSMS+" - "+intent.getStringExtra("WidgetTextSMS"));
			Log.d("_TextMissed_a1_", "Widget onReceive Call "+ myTextCall+" - "+intent.getStringExtra("WidgetTextCALL"));
		}
		
		if(intent.getAction().equals(UPDATE_PREFERENCE)) { //update preference
			updateWidgetLanguage(context);
		}
	}	
	
	
	//On demand language updater
	public void updateWidgetLanguage(Context context) {
		//get configuration language
		Locale.getDefault();		
				
		//Get AppWidgetManager
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		//Get widget IDs
		ComponentName thisWidged = new ComponentName(context, MyAppWidget.class);
		int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidged);
		//Update all widget copies
		for (int i = 0; i < appWidgetIds.length; i++) {
			int appWidgetId = appWidgetIds[i];
			//Get RemoteViews
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
			
			//Update layout
			updateWidgetLayout(views, context, appWidgetId);
			//Save changes
			appWidgetManager.updateAppWidget(appWidgetId, views);
		}		
	}
	
	//updateWidgetLayout after changes
	private void updateWidgetLayout(RemoteViews views, Context context, int appWidgetId){
		//views.setTextViewText(R.id.tvWidgetText1, context.getString(R.string.tvWidgetText1));		
		//views.setTextViewText(R.id.tvWidgetText3, context.getString(R.string.tvWidgetText3));		
		
		//load preferences			
		String[] parameters = AppWidgetConfigure.getParameters(context, appWidgetId);
		Boolean noneAlternative = Boolean.parseBoolean(parameters[0]);
		Boolean enableMsg = Boolean.parseBoolean(parameters[1]);
		//Integer sizeMsg = Integer.parseInt(parameters[3]);
		//Log.d("_TextMissed_a1_", "updateWidgetLayout SMS "+ myTextSMS+"  sizeMsg: "+parameters[3]);
		
		Integer sizeMsg = 10;
		if (parameters[3] != "null") sizeMsg= Integer.parseInt(parameters[3]); 
		Integer sizeMsgNumber = 12;
		if (parameters[4] != "null") sizeMsgNumber = Integer.parseInt(parameters[4]); 		

		//Log.d("_TextMissed_a1_", "updateWidgetLayout SMS "+ myTextSMS+"  parameters[1]: "+parameters[1]+" parameters[2]:"+parameters[2]);
		//Log.d("_TextMissed_a1_", "updateWidgetLayout SMS "+ myTextSMS+"  parameters[3]: "+parameters[3]+" _ "+sizeMsg+" parameters[4]:"+parameters[4]+" _ "+sizeMsgNumber);
		
		if (enableMsg) {
			String text = context.getString(R.string.tvWidgetText1); 		 
	        Paint  mPaint = new Paint();
	        mPaint.setAntiAlias(true);
	        mPaint.setTextSize(sizeMsg);
	        mPaint.setColor(0xffffffff);
	        mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL));
	        float w = mPaint.measureText(text, 0, text.length());
	        int olo = (int) w;
	        // Create an empty, mutable bitmap
			Bitmap bitmap = Bitmap.createBitmap(olo, 13+5, Bitmap.Config.ARGB_4444);
			// get a canvas to paint over the bitmap
			Canvas canvas = new Canvas(bitmap);
			bitmap.eraseColor(0);
			canvas.drawText(context.getString(R.string.tvWidgetText1), 0,15, mPaint);
			
			views.setImageViewBitmap(R.id.tvWidgetText1, bitmap);
			views.setViewVisibility(R.id.tvWidgetText1, View.VISIBLE); //View.VISIBLE
			
			if (myTextSMS == null) myTextSMS = "0";
			String textSMS = myTextSMS;
			
			//0 is zero
			if (noneAlternative) {
				textSMS = findStringIdinArrayXML(myTextSMS, context);
				//views.setTextViewText(R.id.tvWidgetText2, findStringIdinArrayXML(myTextSMS, context));
				//views.setTextViewText(R.id.tvWidgetText4, findStringIdinArrayXML(myTextCall, context));
			} 
			
			//text = context.getString(R.string.tvWidgetText2); 		 
	        mPaint = new Paint();
	        mPaint.setAntiAlias(true);
	        mPaint.setTextSize(sizeMsgNumber);
	        mPaint.setColor(0xffffffff);
	        mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD));
	        w = mPaint.measureText(textSMS, 0, textSMS.length());
	        olo = (int) w;
	        // Create an empty, mutable bitmap
			bitmap = Bitmap.createBitmap(olo, 13+5, Bitmap.Config.ARGB_4444);
			// get a canvas to paint over the bitmap
			canvas = new Canvas(bitmap);
			bitmap.eraseColor(0);
			canvas.drawText(textSMS, 0,15, mPaint);
			
			views.setImageViewBitmap(R.id.tvWidgetText2, bitmap);
			views.setViewVisibility(R.id.tvWidgetText2, View.VISIBLE); //View.VISIBLE
		} else {
			views.setViewVisibility(R.id.tvWidgetText1, View.GONE); //View.VISIBLE
			views.setViewVisibility(R.id.tvWidgetText2, View.GONE); //View.VISIBLE
		}

		Log.d("_TextMissed_a1_", "updateWidgetLayout SMS "+ myTextSMS+"  enableMsg: "+parameters[1]+" sizeMsgNumber:"+sizeMsgNumber);
		
	}
	
	//On demand updater
	public void updateWidget(Context context, String myTextSMS, String myTextCall) {
		//get configuration language
		Locale.getDefault();
		
		//Get AppWidgetManager
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		//Get widget IDs
		ComponentName thisWidged = new ComponentName(context, MyAppWidget.class);
		int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidged);
		//Update all widget copies
		for (int i = 0; i < appWidgetIds.length; i++) {
			int appWidgetId = appWidgetIds[i];
			//Get RemoteViews
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
			
			//load preferences			
			String[] parameters = AppWidgetConfigure.getParameters(context, appWidgetId);
			Boolean noneAlternative = Boolean.parseBoolean(parameters[0]);
			Integer sizeMsg = 10;
			if (parameters[3] != "null") sizeMsg= Integer.parseInt(parameters[3]); 
			Integer sizeMsgNumber = 12;
			if (parameters[4] != "null") sizeMsgNumber = Integer.parseInt(parameters[4]);
			
			//update sms number
			if (myTextSMS == null) myTextSMS = "0";
			String textSMS = myTextSMS;
			
			//0 is zero
			if (noneAlternative) {
				textSMS = findStringIdinArrayXML(myTextSMS, context);
				//views.setTextViewText(R.id.tvWidgetText2, findStringIdinArrayXML(myTextSMS, context));
				//views.setTextViewText(R.id.tvWidgetText4, findStringIdinArrayXML(myTextCall, context));
			} 
			
			//text = context.getString(R.string.tvWidgetText2); 		 
			Paint  mPaint = new Paint();
	        mPaint.setAntiAlias(true);
	        mPaint.setTextSize(sizeMsgNumber);
	        mPaint.setColor(0xffffffff);
	        mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD));
	        float w = mPaint.measureText(textSMS, 0, textSMS.length());
	        int olo = (int) w;
	        // Create an empty, mutable bitmap
			Bitmap bitmap = Bitmap.createBitmap(olo, 13+5, Bitmap.Config.ARGB_4444);
			// get a canvas to paint over the bitmap
			Canvas canvas = new Canvas(bitmap);
			bitmap.eraseColor(0);
			canvas.drawText(textSMS, 0,15, mPaint);
			
			views.setImageViewBitmap(R.id.tvWidgetText2, bitmap);
		
			
			
			//Save changes
			appWidgetManager.updateAppWidget(appWidgetId, views);
			
			Log.d("_TextMissed_a1_", "Widget updateWidget");

			
		}
	}
	
	//zamien string na id w tablicy strings.xml
	private String findStringIdinArrayXML(String find, Context context) {
		String smsNumber="";
		String nmbToFind = "number00"+find;
		if (Integer.parseInt(find) == 0)
			smsNumber = context.getString(context.getResources().getIdentifier(nmbToFind, "string", context.getPackageName()));
		else if (Integer.parseInt(find) > 0 && Integer.parseInt(find) < 10 )
			smsNumber = context.getString(context.getResources().getIdentifier(nmbToFind, "string", context.getPackageName()));
		else if (Integer.parseInt(find) >= 10 && Integer.parseInt(find) < 100 ){
			nmbToFind = "number0"+find;
			smsNumber = context.getString(context.getResources().getIdentifier(nmbToFind, "string", context.getPackageName()));
		}
		else 
			smsNumber = find;
		
		return smsNumber;
	}
	
	@Override
	public void onDisabled(Context context) {
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onDisabled ");
		// TODO Auto-generated method stub
		super.onDisabled(context);
	}

	@Override
	public void onEnabled(Context context) {
		Log.d("_TextMissed_a1_", "++++++++++++++Widget onEnabled ");
		// TODO Auto-generated method stub
		super.onEnabled(context);
		
		//start service 
		context.startService(new Intent(context, MyService.class));
	}
    
    //showToast
    public void showToast(String text) {
        toast.setText(text);
        toast.show();
    }
}